package com.qf.business.auth.controller;

import com.alibaba.fastjson.JSON;
import com.qf.business.auth.service.IAuthService;
import com.qf.commons.base.result.R;
import com.qf.commons.base.result.Rs;
import com.qf.commons.base.user.BaseUser;
import com.qf.commons.core.utils.JwtUtils;
import com.qf.data.auth.vo.input.AuthLoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * spring security + oauth2
 * author Ken
 * create_time 2022/11/25
 */
@RestController
@RequestMapping("/auth")
@Slf4j
public class AuthController {

    /**
     * 获得IOC容器对象
     */
    @Autowired
    private ApplicationContext applicationContext;

    @RequestMapping("/login")
    public R login(AuthLoginVo authLoginVo, @RequestHeader("fromType") Integer fromType){
        log.debug("[login] 用户登录 - {} - 请求来源：{}", authLoginVo, fromType);
        //通过不同的客户端来源获取 认证业务的实现类
        IAuthService authService = (IAuthService) applicationContext.getBean("authService" + fromType);
        BaseUser loginUser = authService.login(authLoginVo);
        log.debug("[login] 用户登录成功，获取用户信息 - {}", loginUser);
        //通过jwt 将用户信息 转换成登录令牌，返回给客户端
        String jwtToken = JwtUtils.createJwtToken("user", JSON.toJSONString(loginUser));
        log.debug("[login] 用户登录的令牌 - {}", jwtToken);
        return Rs.create(jwtToken);
    }
}
